import axios from "axios";
import { ElMessage } from "element-plus";
import router from "../router/index";

//定义访问基础路径
const baseURL = "https://skygray.top:5443";

const axiosInstance = axios.create({
  baseURL,
  timeout: 15000, //15秒超时,
  headers: {
    "Content-Type": "application/json",
  },
});

/**
 * 请求拦截
 */
axiosInstance.interceptors.request.use(
  function (config) {
    // 打开 loading
    const token: string | null = sessionStorage.getItem("token");
    if (token) {
      config.headers["Authorization"] = token;
    }
    return config;
  },
  function (error) {
    // 对请求错误做些什么
    return Promise.reject(error);
  }
);

/**
 * 响应拦截
 */
axiosInstance.interceptors.response.use(
  function (response) {
    const status = response.data.code;
    switch (status) {
      case 401:
        ElMessage.error("身份验证失败，请重新登录");
        sessionStorage.clear();
        router.replace({
          path: "/smart-e/admin/login",
        });
        break;
    }
    // 对响应数据做点什么
    return response;
  },
  function (error) {
    // 对响应错误做点什么
    console.log(error.response?.data.code);

    return Promise.reject(error);
  }
);

export default axiosInstance;
export const request = axiosInstance.request;
